<template>
  <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="80%"
    :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-col :span="6" v-for="item, index in tableThead" :key="index" v-show="item.slotName !== 'seeDetail'" >
          <div class="info" :style="{ lineHeight: '30px', fontSize: '16px' }">
            <span>{{ item.label }}：</span>
            <span v-if="item.slotName">{{ ruleForm[item.slotName] }}</span>
            <span v-else-if="item.prop">{{ ruleForm[item.prop] }}</span>
          </div>
        </el-col>
      <div class="elrowBox">
        <el-table :data="ruleForm.detailList" height="400"  style="width: 100%" border>
          <el-table-column :label="itemson.label" :width="itemson.width||''" v-for="itemson, indexson in dialogtableThead"
            :key="indexson">
            <template slot-scope="scope">
              <div v-if="itemson.slotName">
                {{ scope.row[itemson.slotName] && JSON.parse(scope.row[itemson.slotName]).name || '' }}</div>
              <div v-else-if="itemson.prop">{{ scope.row[itemson.prop] || '' }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
    </span>
  </el-dialog>
</template>
<script>
import ncfeedingApi from "@/api/production-management-nc/feeding-operation-nc";
import ncBasicinfoApi from "@/api/nc-basic-info/index";
import ncproductionApi from "@/api/production-management-nc/index";

export default {
  components: {},
  props: {
    addEditFlag: {
      type: String,
      default: () => {
        return "add";
      },
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    title: {
      type: String,
      default: () => {
        return "操作表单";
      },
    },
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    tableThead: {
      type: Array,
      default: () => {
        return [];
      },
    },
    dialogtableThead: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      addEditName: "添加",
      addEditApi: "",
      ruleForm: {},
      MaterialconvertList: [], //辅单位
      BatchcodeList: [],
      rules: {},
    };
  },
  computed: {},
  watch: {
    dialogVisible(v) {
      v && this.initData();
    },
  },
  mounted() { },
  methods: {
    returnData(data) {
      return data && JSON.parse(data).name;
    },
    initData() {
      if (this.addEditFlag == "add") {
        this.resetForm();
        this.addEditApi = ncfeedingApi.add;
        this.addEditName = "添加";
        this.ruleForm = {
          ctrantypeid: "4D-01",
          vtrantypecode: "4D-01",
          type: "FEED",
          detailList: [
            {
              cmaterialvid: "",
              vproductbatch: "",
              vbatchcode: "",
              nshouldassistnum: "",
              nshouldnum: "",
              nnum: "",
              nassistnum: "",
              vbdef1: "",
              vbdef2: "",
            },
          ],
        };
      } else if (this.addEditFlag == "edit") {
        this.ruleForm = { ...this.data };
        this.ruleForm = this.convertFieldsToName(
          { ...this.data },
          this.tableThead
        );
        this.addEditApi = ncfeedingApi.edit;
        this.addEditName = "查看";
      }
    },
    convertFieldsToName(jsonData, fields) {
      // 遍历所有需要转换的字段
      fields.forEach((field) => {
        // 确保该字段存在并且是一个字符串
        if (
          jsonData[field.slotName] &&
          typeof jsonData[field.slotName] === "string"
        ) {
          try {
            // 将字段的值解析为 JSON 对象
            const fieldValue = JSON.parse(jsonData[field.slotName]);
            // 如果 JSON 对象中有"name"字段，则将其值赋给原字段
            if (fieldValue.name) {
              jsonData[field.slotName] = fieldValue.name;
            }
          } catch (error) {
            console.error(
              `Error parsing JSON for field ${field}: ${error.message}`
            );
          }
        }
      });
      console.log(jsonData);
      return jsonData;
    },
    pushData(data) {
      this.ruleForm = { ...data };
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    //领料部门
    changecdptvid(e) {
      // let rut = this.OrgDeptList.find((item) => {
      //   return e == item.code;
      // });
      this.$set(this.ruleForm, "cdptid", e);
    },
    //物料修改
    async changeMaterial(e, index) {
      let rut = this.MaterialList.find((item) => {
        return e == item.code;
      });
      rut.measrate = "1/1";
      let obj = this.ruleForm.detailList[index];
      obj.cunitid = rut.measdoccode;
      obj.vproductbatch = null;
      obj.vchangerate = null;
      obj.castunitid = null;
      obj.vbatchcode = null;
      let resMaterialconvert = await ncBasicinfoApi.queryMaterialconvert({
        pk_material: rut.pk_material,
      });
      let list = resMaterialconvert.data || [];
      let MaterialObj = list.find((item) => {
        return item.measdoccode === rut.measdoccode;
      });
      if (!MaterialObj) {
        list.push(rut);
      }

      if (list.length >= 1) {
        obj.vchangerate = list[0].measrate;
        obj.castunitid = list[0].measdoccode;
      }
      let resBatchcode = await ncproductionApi.queryBatchcode({
        entity: { cmaterialvid: rut.pk_material },
        page: 1,
        size: 1000,
      });
      this.$set(this.BatchcodeList, index, resBatchcode.data.content || []);
      this.$set(this.MaterialconvertList, index, list);
      this.$set(this.ruleForm.detailList, index, obj);
    },

    //辅助物料
    changeMaterialconvert(e, index) {
      let rut = this.MaterialconvertList[index].find((item) => {
        return e == item.measdoccode;
      });

      let obj = this.ruleForm.detailList[index];
      obj.vchangerate = rut ? rut.measrate : null;
      obj.nshouldassistnum = null;
      obj.nshouldnum = null;
      obj.nassistnum = null;
      obj.nnum = null;
      this.$set(this.ruleForm.detailList, index, obj);
    },

    // 批次号
    handleChangevbatchcode(e, row) {
      let vbatchcode = row.vbatchcode;
      row.vproductbatch = vbatchcode;
    },

    // 养殖批次号
    handleChangevproductbatch(e, row) {
      console.log(e, row);
    },

    //应发主数量
    handleChangenshouldnum(e, index) {
      let rut = this.ruleForm.detailList[index];
      if (!rut.nshouldnum) {
        return;
      } else {
        let nshouldnum = Number(rut.nshouldnum);
        let vchangerateList = rut.vchangerate
          ? rut.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          rut.nshouldassistnum = nshouldnum / Number(vchangerateList[0]);
          this.$set(this.ruleForm.detailList, index, rut);
        }
      }
    },

    //应发辅数量
    handleChangenshouldassistnum(e, index) {
      let rut = this.ruleForm.detailList[index];
      if (!rut.nshouldassistnum) {
        return;
      } else {
        let nshouldassistnum = Number(rut.nshouldassistnum);
        let vchangerateList = rut.vchangerate
          ? rut.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          rut.nshouldnum = nshouldassistnum * Number(vchangerateList[0]);
          this.$set(this.ruleForm.detailList, index, rut);
        }
      }
    },

    //实发主数量
    handleChangennum(row) {
      if (!row.nnum) {
        return;
      } else {
        let nnum = (row.nnum = Number(row.nnum));
        let vchangerateList = row.vchangerate
          ? row.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          row.nassistnum = nnum / Number(vchangerateList[0]);
        }
      }
    },

    //实发辅数量
    handleChangenassistnum(row) {
      if (!row.nassistnum) {
        return;
      } else {
        let nassistnum = Number(row.nassistnum);
        let vchangerateList = row.vchangerate
          ? row.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          row.nnum = nassistnum * Number(vchangerateList[0]);
        }
      }
    },

    addMaterial() {
      let length = this.ruleForm.detailList?.length || 0;
      if (length) {
        this.$set(this.ruleForm.detailList, length, {
          vproductbatch: "",
          vbatchcode: "",
          nshouldassistnum: "",
          nshouldnum: "",
          nnum: "",
          nassistnum: "",
          vbdef1: "",
          vbdef2: "",
        });
      }
    },

    delMaterial(index) {
      let list = this.ruleForm.detailList;
      list.splice(index, 1);
      this.$set(this.ruleForm, "detailList", list);
    },

    //提交表单
    submitForm() {
      console.log(this.ruleForm, "this.ruleForm");
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.ruleForm));
          delete formData.detailList;
          formData.pk_org = this.OrgOrgsList[0].code;
          formData.pk_group = "SSAGROUP";
          let list = [
            {
              ic_material_b: this.ruleForm.detailList,
              ic_material_h: formData,
            },
          ];
          console.log(list);
          this.addEditApi(list)
            .then((res) => {
              let msg = res.success ? "操作成功" : "操作失败";
              this.$message[res.success ? "success" : "warning"](
                res.message || msg
              );
              res.success && this.cancel();
              //提交数据时删除保存的记录
              res.success && this.addEditFlag == "add";
            })
            .catch((err) => {
              this.$message.error(err);
            });
        } else {
          return false;
        }
      });
    },
    //重置
    resetForm() {
      this.ruleForm = {};
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
    },
    //取消关闭
    cancel() {
      this.resetForm();
      this.$emit("closeDialog");
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.resetForm();
          this.cancel();
        })
        .catch((_) => { });
    },
  },
};
</script>
<style lang="scss" scoped>
.line {
  border-bottom: 1px solid #e6e6e6;
}

.icon {
  font-size: 20px;
  line-height: 29px;
  cursor: pointer;
}

::v-deep .noLabel {
  .el-form-item {
    .label {
      display: none;
    }

    .el-form-item__content {
      margin: 0;
    }
  }
}

// .demo-ruleForm{
//   display: flex;
//   .w100p{
//     width: 100%;
//   }
// }
.elrowBox {

  .elrowBoxItem {
    border: 1px #969595 dashed;
    margin-bottom: 20px;
  }

  .elrowBoxInput {
    min-width: 120px;
  }

  .elrowBoxlabel {
    width: 200px;
    // overflow-x: auto;
    // overflow: hidden; /* 隐藏溢出内容 */
    // text-overflow: ellipsis; /* 当文本溢出时显示省略号 */
    white-space: nowrap;
    /* 禁止文本换行 */
    background-color: #e1e1e1;
  }
}
</style>